import commonUtils from './common.js'
import config from '../config.js'

export * from './request.js'
export * from './getPageConfigData.js'
export * from './evalFn.js'
export * from './wx.js'

export const getImgs = (imgStrs) => {
	const list = JSON.parse(imgStrs)
	return list.map(l => `${config.BASE_URL}/action/fileapi/fileget?fileid=${l.i}`)
}

export const getImg = (imgStrs) => {
	if (typeof imgStrs === 'string') {
		const list = JSON.parse(imgStrs)
		return list.map(l => `${config.BASE_URL}/action/fileapi/fileget?fileid=${l.i}`)[0]
	}
	if (imgStrs) {
		return `${config.BASE_URL}/action/fileapi/fileget?fileid=${imgStrs.i}`
	}
	return ''
}

// 组合函数
export function composeFns(...fns) {
	return function(value) {
		let result = value
		for (const fn of fns) {
			result = fn(result)
		}
		return result
	}
}

// 换行替换成br标签
export function convertNewlinesToBr(str) {
	return str.replace(/\n/g, '<br>');
}


export function debounce(fn, delay = 200) {
	let timer
	return function() {
		let context = this
		let args = [...arguments]
		if (timer) {
			clearTimeout(timer)
		}
		timer = setTimeout(() => {
			fn.apply(context, args)
			timer = null
		}, delay)
	}
}

export function throttle(fn, wait = 200) {
	let timer = null
	return function() {
		const that = this
		const args = [...arguments]
		if (timer) return
		fn.apply(that, args)
		timer = setTimeout(() => {
			timer = null
		}, wait)
	}
}


export function encodeQueryData(data) {
  return Object.keys(data)
      .map(key => encodeURIComponent(key) + '=' + encodeURIComponent(data[key]))
      .join('&');
}

export default  commonUtils